/**
 * 并发控制
 */
function requestLimit(taskList, limit = 3) {
    return new Promise((resolve, reject) => {

        let runningCount = 0;
        let nextIndex = 0;
        let completedCount = 0;
        const result = Array(taskList.length);

        function runTask() {
            if(runningCount === limit || nextIndex === taskList.length) {
                return;
            }
            runningCount++;
            const curIndex = nextIndex++;
            const task = taskList[curIndex];
            Promise.resolve(typeof task === 'function' ? task() : task)
            .then(res => result[curIndex] = res)
            .catch(error => result[curIndex] = error)
            .finally(() => {
                runningCount--;
                completedCount++;
                if (completedCount === taskList.length) {
                    resolve(result);
                } else {
                    runTask();
                }
            });
        }

        for(let i = 0; i < Math.min(limit, taskList.length); i++) {
            runTask();
        }
    });
}